﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMessageBox>
#include <QDebug>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    InitTree();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::InitTree()
{
    //1，构造Model，这里示例具有3层关系的model构造过程
    mModel = new QStandardItemModel(ui->treeView);
    mModel->setHorizontalHeaderLabels(QStringList()<<QStringLiteral("序号") << QStringLiteral("名称"));     //设置列头

    for(int i=1;i<5;i++)
    {
        //一级节点，加入mModel
        QList<QStandardItem*> items1;
        QStandardItem* item1 = new QStandardItem(QString::number(i));
        QStandardItem* item2 = new QStandardItem(QStringLiteral("1级节点"));
        items1.append(item1);
        items1.append(item2);
        mModel->appendRow(items1);

        for(int j=1;j<5;j++)
        {
            //二级节点,加入第1个一级节点
            QList<QStandardItem*> items2;
            QStandardItem* item3 = new QStandardItem(QString::number(j));
            QStandardItem* item4 = new QStandardItem(QStringLiteral("2级节点-%1-%2").arg(i).arg(j));
            items2.append(item3);
            items2.append(item4);
            item1->appendRow(items2);

            for(int k=1;k<5;k++)
            {
                //三级节点,加入第1个二级节点
                QList<QStandardItem*> items3;
                QStandardItem* item5 = new QStandardItem(QString::number(k));
                QStandardItem* item6 = new QStandardItem(QStringLiteral("3级节点-%1-%2-%3").arg(i).arg(j).arg(k));
                items3.append(item5);
                items3.append(item6);
                item3->appendRow(items3);
            }
        }
    }
    //2，给QTreeView应用model
    ui->treeView->setModel(mModel);

    connect(ui->treeView,&QTreeView::pressed,this,&MainWindow::slotTreePressed);
    connect(ui->treeView,&QTreeView::clicked,this,&MainWindow::slotTreeClicked);
    connect(ui->treeView,&QTreeView::doubleClicked,this,&MainWindow::slotTreeDoubleClicked);

}


void MainWindow::slotTreePressed(const QModelIndex &index)
{
    QStandardItem* item = mModel->itemFromIndex(index);
    ui->textEdit->append("Pressed " + item->text());
}

void MainWindow::slotTreeClicked(const QModelIndex &index)
{
    QStandardItem* item = mModel->itemFromIndex(index);
    ui->textEdit->append("Clicked " + item->text());
}

void MainWindow::slotTreeDoubleClicked(const QModelIndex &index)
{
    QStandardItem* item = mModel->itemFromIndex(index);
    ui->textEdit->append("DoubleClicked " + item->text());
}



